package cn.com.platform.web.pub.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.com.easy.dto.MessageDTO;
import cn.com.easy.utils.HttpUtils;
import cn.com.easy.utils.ResponseOutputUtils;

/**
 * 临时图片访问控制器
 * 
 * @author nibili 2016年8月22日
 * 
 */
@Controller
@RequestMapping("/upload")
public class ImageController {

	/** 上传路径 */
	@Value("${fileupload.path}")
	private String rootPath;

	/**
	 * 访问图片
	 * 
	 * @param modelMap
	 * @param req
	 * @param res
	 * @param path
	 * @author nibili 2016年8月22日
	 */
	@RequestMapping("/**")
	public void index(ModelMap modelMap, HttpServletRequest req, HttpServletResponse res) {

		try {
			String url = "";
			String uri = req.getRequestURI();
			uri = java.net.URLDecoder.decode(uri, "UTF-8");
			if (uri.indexOf("http://") > -1) {
				// 是http图片，
				url = uri.replaceAll(".*(http://.*)", "$1");
				FileCopyUtils.copy(HttpUtils.deGetFileInputSteam(url), res.getOutputStream());
			} else {
				String path = rootPath + "/" + uri.replaceAll("/upload", "");
				byte[] bytes = FileUtils.readFileToByteArray(FileUtils.getFile(path));
				FileCopyUtils.copy(bytes, res.getOutputStream());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 上传图片文件
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public void upload(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile file) throws Exception {
		// logger.info("项目classloader根路径:" +
		// ImgService.class.getResource("/").getPath());

		if (validateFile(file)) {
			String fileName = upload(file.getOriginalFilename(), file.getInputStream());
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, fileName));
		} else {
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, ""));
		}
	}

	/**
	 * 上传图片
	 * 
	 * @param filename
	 *            文件名称
	 * @param is
	 * @return
	 * @throws IOException
	 * @auth nibili 2015年1月11日 上午11:13:01
	 */
	private String upload(String filename, InputStream is) throws IOException {
		String imgName = System.currentTimeMillis() + filename.substring(filename.indexOf("."));
		FileUtils.copyInputStreamToFile(is, new File(rootPath, imgName));
		return imgName;
	}

	/**
	 * 验证图片
	 * 
	 * @param img
	 * @return
	 */
	private boolean validateFile(MultipartFile img) {
		if (img != null && !img.isEmpty()) {
			String type = img.getContentType(); // 文件类型
			if (type.indexOf("image") != -1) {
				// 图片
				return true;
			}
		}
		return false;
	}

}
